<template>
  <div>
    <el-tree ref="treeRef" :data="treeList" :props="treeProps" node-key="id" show-checkbox default-expand-all
      :default-checked-keys="checkList"></el-tree>
    <div class="button-box">
      <el-button type="primary" @click="preservation">保存</el-button>
      <el-button @click="cancel">清空</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ApiTreeList, ApiRoleList, ApiAllocMenu } from "./api";
import { useRoute, useRouter } from "vue-router";
import { ref } from "vue";
import type Node from "element-plus/es/components/tree/src/model/node";
import { ElMessage, ElMessageBox, ElTree } from "element-plus";

const route = useRoute();
const router = useRouter();
// 获取真实dom
const treeRef = ref<InstanceType<typeof ElTree>>();

const treeList = ref<ITreeList[]>([]);
// 勾选上的数组
const checkList = ref<any[]>([]);
const treeProps = {
  //   label 是告诉 tree组件，在data里面哪个属性是用来显示文字的
  label: "title",
  // children属性是要告诉 tree 组件，在data里面哪个属性名是用来作用子级的
  children: "children",
};

if (route.query.id) {
  Promise.all([
    ApiTreeList(),
    ApiRoleList(parseInt(route.query.id as string)),
  ]).then((res) => {
    if (res[0].code === 200) {
      treeList.value = res[0].data;
    }
    checkList.value = res[1].data.map((item) => {
      if (item.parentId !== 0) {
        return item.id;
      }
    });
  });
}
// 清空
const cancel = () => {
  treeRef.value!.setCheckedKeys([], false);
};
// 保存
const preservation = () => {
  // 全选加半选
  //   treeRef.value!.getCheckedKeys(false);是所有勾选的id的数组
  // treeRef.value!.getHalfCheckedKeys()是所有半选的id的数组
  // 发送请求的时候需要包含一级标题的id，渲染数据的时候不需要带上一级标题的id，如果渲染数据的时候带上一级标题的id就会勾上一级标题的复选框，它下面的二级那些复选框原来没勾上的也全都会勾上
  let checkAll = treeRef
    .value!.getCheckedKeys(false)
    .concat(treeRef.value!.getHalfCheckedKeys());
  ElMessageBox.confirm("此操作将保存当前用户, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    ApiAllocMenu({
      roleId: parseInt(route.query.id as string),
      menuIds: checkAll,
    }).then((res) => {
      if (res.code === 200) {
        // 提示
        ElMessage.success("保存成功");
        // 跳转
        router.push("/ums/role");
      }
    });
  });
};
</script>

<style scoped>
.button-box {
  text-align: center;
}
</style>
